package leetcode.D600.T581;

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int max = nums[0], min = nums[nums.length-1], left = -1, right = -1;
        for (int i=1; i<nums.length; ++i) {
            if (nums[i] < max)
                right = i;
            max = Math.max(max, nums[i]);
        }
        if (right < 0)
            return 0;
        for (int i=nums.length-1; i>=0; --i) {
            if (nums[i] > min)
                left = i;
            min = Math.min(min, nums[i]);
        }
        return right - left + 1;
    }
}
